#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <fcntl.h>
#include <time.h>
#include <sys/ioctl.h>
#include <linux/ioctl.h>
#include <sys/stat.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>
#include <math.h>
#include <time.h>
struct IMUDATA {
  int16_t accx;
  int16_t accy;
  int16_t accz;
  int16_t gyrox;
  int16_t gyroy;
  int16_t gyroz;
  int16_t magx;
  int16_t magy;
  int16_t magz;
  long timestamp;
};
double G=9.7940;
int main(int argc, char *argv[]) {
  int fd = open("/dev/spidev0.0", O_RDWR);
  if (fd < 0) {
    printf("can't open device\n");
    return 0;
  }
  printf("ok to open device,any key to continue!\n");
  //getchar();
  struct IMUDATA imudata;
  for (int i = 0;; i++) {
    ssize_t ret = read(fd, &imudata, sizeof(struct IMUDATA));
    if (ret > 0) {
      float g = sqrt(((float)imudata.accx * (float)imudata.accx + (float)imudata.accy * (float)imudata.accy + (float)imudata.accz * (float)imudata.accz)) * 24.0 / 32767.0;
      struct timespec tp;
      long long time_ns = 0;

      clock_gettime(CLOCK_MONOTONIC, &tp);
      time_ns = (long long)tp.tv_sec * 1000000000 + tp.tv_nsec;

      float gyrox=(float)imudata.gyrox * 1000.0 / 32767.0;
      float gyroy=(float)imudata.gyroy * 1000.0 / 32767.0;
      float gyroz= (float)imudata.gyroz * 1000.0 / 32767.0;
      printf("ret:%ld,tmoffset:%lld\n"
             "accx:%f\n"
             "accy:%f\n"
             "accz:%f\n"
             "accg:%f m/s2\n"
             "gyrox:%f degree/s,%f rad/s\n"
             "gyroy:%f degree/s,%f rad/s\n"
             "gyroz:%f degree/s,%f rad/s\n"
             "magx:%f\n"
             "magy:%f\n"
             "magz:%f\n",
             ret, time_ns - imudata.timestamp, imudata.accx * 24.0 / 32767.0,
             imudata.accy * 24.0 / 32767.0,
             imudata.accz * 24.0 / 32767.0, g*G,
             gyrox,gyrox*M_PI/180.0,gyroy,gyroy*M_PI/180.0,gyroz,gyroz*M_PI/180.0,
             (float)imudata.magx, (float)imudata.magy, (float)imudata.magz);
    }
    // usleep(100);
  }
  close(fd);

  return 0;
}
